package com.linq.cool.beauty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linq.cool.api.domain.BeautyMember;
import com.linq.cool.api.domain.BeautyMemberItem;
import com.linq.cool.beauty.domain.BeautyTopUp;
import com.linq.cool.beauty.dto.BeautyTopUpQueryDTO;
import com.linq.cool.beauty.dto.BeautyTopUpSelfQueryDTO;
import com.linq.cool.beauty.mapper.BeautyTopUpLogMapper;
import com.linq.cool.beauty.service.BeautyMemberItemService;
import com.linq.cool.beauty.service.BeautyTopUpService;
import com.linq.cool.beauty.vo.statistical.MonthlyIncomeVO;
import com.linq.cool.beauty.vo.statistical.StatisticalVO;
import com.linq.cool.common.constants.Constants;
import com.linq.cool.common.constants.UserConstants;
import com.linq.cool.common.core.utils.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Author: yqlin
 * @Date: 2021/2/2 22:37
 * @Description:
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class BeautyTopUpServiceImpl extends ServiceImpl<BeautyTopUpLogMapper, BeautyTopUp> implements BeautyTopUpService {
    @Autowired
    private BeautyMemberServiceImpl beautyCustomerService;
    @Autowired
    private BeautyMemberItemService beautyCustomerItemService;
    @Autowired
    private IdWorker idWorker;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void paySuccess(String orderId, String payPlatformId, Integer payType) {
        //根据支付订单ID查询支付订单日志
        BeautyTopUp topUpLog = this.getById(orderId);
        // 充值用户金额
        BeautyMember member = beautyCustomerService.getById(topUpLog.getMemberId());
        member.setAmount(member.getAmount().add(topUpLog.getAmount()))
                .setHistoryAmount(member.getHistoryAmount().add(topUpLog.getAmount()))
                .setGmtModified(new Date());
        beautyCustomerService.updateById(member);
        // 更新充值记录
        topUpLog.setMemberPhone(member.getPhone())
                .setMemberRealName(member.getRealName())
                //设置平台交易编号
                .setPayPlatformId(payPlatformId)
                //设置支付类型
                .setPayType(payType)
                //设置支付时间
                .setPayTime(new Date())
                //已支付
                .setStatus(UserConstants.StateEnum.ORDER_STATUS_1.getCode())
                .setGmtModified(new Date());
        this.updateById(topUpLog);
        // 查询客户字表信息 如果第一次充值 就是保存 否则就是更新
        BeautyMemberItem memberItem = beautyCustomerItemService.getOne(new LambdaQueryWrapper<BeautyMemberItem>()
                                                                               .eq(BeautyMemberItem::getMemberId, member.getId())
        );
        // 第一次充值
        if (null == memberItem) {
            log.info("{}第一次充值", member.getPhone());
            memberItem = new BeautyMemberItem();
            // 保存客户子表信息
            memberItem
                    .setId(idWorker.nextId())
                    .setMemberId(member.getId())
                    .setMemberRealName(member.getRealName())
                    .setMemberPhone(member.getPhone())
                    .setTopUpCount(1)
                    // 累计消费
                    .setConsumeAmount(topUpLog.getAmount())
                    // 累计充值
                    .setTopUpAmount(topUpLog.getAmount());
            beautyCustomerItemService.save(memberItem);
        } else {
            // 更新
            memberItem
                    .setTopUpCount(memberItem.getTopUpCount() + 1)
                    .setTopUpAmount(memberItem.getTopUpAmount().add(topUpLog.getAmount()))
                    .setConsumeAmount(memberItem.getConsumeAmount().add(topUpLog.getAmount()))
                    .setGmtModified(new Date());
            beautyCustomerItemService.updateById(memberItem);
        }
    }

    @Override
    public IPage<BeautyTopUp> listByPage(IPage<BeautyTopUp> page, BeautyTopUpQueryDTO dto) {
        return this.page(page, new LambdaQueryWrapper<BeautyTopUp>()
                .orderByDesc(BeautyTopUp::getGmtCreate)
                .eq(StringUtils.checkValNotNull(dto.getId()), BeautyTopUp::getId, dto.getId())
                .like(StringUtils.checkValNotNull(dto.getMemberPhone()), BeautyTopUp::getMemberPhone, dto.getMemberPhone())
                .like(StringUtils.checkValNotNull(dto.getMemberRealName()), BeautyTopUp::getMemberRealName, dto.getMemberRealName())
                .eq(StringUtils.checkValNotNull(dto.getStatus()), BeautyTopUp::getStatus, dto.getStatus())
                .eq(StringUtils.checkValNotNull(dto.getPayType()), BeautyTopUp::getPayType, dto.getPayType())
                .between(StringUtils.checkValNotNull(dto.getParams().get(Constants.BEGIN_TIME)), BeautyTopUp::getGmtCreate, dto.getParams().get(Constants.BEGIN_TIME), dto.getParams().get(Constants.END_TIME))
        );
    }


    @Override
    public IPage<BeautyTopUp> listBySelfPage(IPage<BeautyTopUp> page, BeautyTopUpSelfQueryDTO dto) {
        return this.page(page, this.getLambdaQueryWrapper(dto));
    }

    @Override
    public MonthlyIncomeVO statisticalMonthlyIncome() {
        List<Object> yearMonthList = new LinkedList<>();
        List<Object> totalAmountList = new LinkedList<>();
        List<Map<String, Object>> maps = baseMapper.statisticalMonthlyIncome();
        for (Map<String, Object> map : maps) {
            yearMonthList.add(map.get("year_month"));
            totalAmountList.add(map.get("total_amount"));
        }
        return new MonthlyIncomeVO().setYearMonthList(yearMonthList).setTotalAmountList(totalAmountList);
    }

    @Override
    public List<StatisticalVO> statisticalTopTenSpenders() {
        List<StatisticalVO> list = baseMapper.statisticalTopTenSpenders();
        if (CollectionUtils.isEmpty(list)) {
            StatisticalVO vo = new StatisticalVO();
            vo.setName("暂无").setValue("暂无").setExtra("暂无");
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<StatisticalVO> statisticMemberTopUp(Long memberId) {
        List<StatisticalVO> list = baseMapper.statisticMemberTopUp(memberId);
        if (CollectionUtils.isEmpty(list)) {
            StatisticalVO vo = new StatisticalVO();
            vo.setName("暂无").setValue("暂无").setExtra("暂无");
            list.add(vo);
        }
        return list;
    }

    private LambdaQueryWrapper<BeautyTopUp> getLambdaQueryWrapper(BeautyTopUpSelfQueryDTO dto) {
        return new LambdaQueryWrapper<BeautyTopUp>()
                .eq(BeautyTopUp::getMemberId, dto.getMemberId())
                .eq(StringUtils.checkValNotNull(dto.getId()), BeautyTopUp::getId, dto.getId())
                .eq(StringUtils.checkValNotNull(dto.getStatus()), BeautyTopUp::getStatus, dto.getStatus())
                .eq(StringUtils.checkValNotNull(dto.getPayType()), BeautyTopUp::getPayType, dto.getPayType())
                .between(StringUtils.checkValNotNull(dto.getParams().get(Constants.BEGIN_TIME)), BeautyTopUp::getGmtCreate, dto.getParams().get(Constants.BEGIN_TIME), dto.getParams().get(Constants.END_TIME))
                ;
    }
}
